const { Op } = require('sequelize');
const Reader = require('../models/Reader');

// 获取用户列表（支持分页和搜索）
exports.getUsers = async (ctx) => {
  const { page = 1, size = 10, q = '' } = ctx.query;
  const offset = (page - 1) * size;

  try {
    const where = {};
    if (q) {
      where.username = { [Op.like]: `%${q}%` };
    }

    const { count, rows } = await Reader.findAndCountAll({
      where,
      limit: parseInt(size),
      offset: parseInt(offset),
      attributes: { exclude: ['password'] } // 不返回密码
    });

    ctx.body = {
      content: rows,
      totalElements: count
    };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

// 创建用户
exports.createUser = async (ctx) => {
  const { username, password, role } = ctx.request.body;
  try {
    const reader = await Reader.create({ username, password, role });
    const { password: _, ...userWithoutPassword } = reader.toJSON();
    ctx.status = 201;
    ctx.body = userWithoutPassword;
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

// 更新用户
exports.updateUser = async (ctx) => {
  const { id } = ctx.params;
  const { username, role } = ctx.request.body;
  try {
    const reader = await Reader.findByPk(id);
    if (!reader) {
      ctx.status = 404;
      ctx.body = { error: 'User not found' };
      return;
    }
    await reader.update({ username, role });
    const { password, ...userWithoutPassword } = reader.toJSON();
    ctx.body = userWithoutPassword;
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

// 更新用户状态
exports.updateUserStatus = async (ctx) => {
  const { id } = ctx.params;
  const { status } = ctx.request.body;
  try {
    const reader = await Reader.findByPk(id);
    if (!reader) {
      ctx.status = 404;
      ctx.body = { error: 'User not found' };
      return;
    }
    await reader.update({ status });
    ctx.body = { message: 'Status updated successfully' };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

// 删除用户
exports.deleteUser = async (ctx) => {
  const { id } = ctx.params;
  try {
    const result = await Reader.destroy({ where: { reader_id: id } });
    if (result === 0) {
      ctx.status = 404;
      ctx.body = { error: 'User not found' };
      return;
    }
    ctx.status = 204; // No Content
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};